import { useRequest } from 'ahooks';
import React from 'react';
import Mock from 'mockjs';
import { Divider } from 'antd';

function getUsername() {
  console.log('polling getUsername');
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(Mock.mock('@name'));
    }, 1000);
  });
}

const boxStyle = {
  margin: '10px',
  border: '1px solid #ccc',
  borderRadius: '10px',
  padding: '10px',
}

export default () => {
  const { data, loading, run, cancel } = useRequest(getUsername, {
    pollingInterval: 1000, // 进入轮询模式
    pollingWhenHidden: false, // 在页面隐藏时，是否继续轮询。如果设置为 false，在页面隐藏时会暂时停止轮询，页面重新显示时继续上次轮询。
    pollingErrorRetryCount: 1, // 轮询错误重试次数。如果设置为 -1，则无限次
  }); 

  return (
    <div style={boxStyle}>
      <Divider>useRequest 轮询使用</Divider>
      <p>Username: {loading ? 'Loading' : data}</p>
      <button type="button" onClick={run}>
        start
      </button>
      <button type="button" onClick={cancel} style={{ marginLeft: 16 }}>
        stop
      </button>
    </div>
  );
};